package com.wangan;

import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {
        // 获取 java 版本
        String version = System.getProperty("java.specification.version");

        // 获取系统类型
        String platform = System.getProperty("os.name", "");
        platform = platform.toLowerCase().contains("window") ? "win" : "linux";

        // 当前程序目录
        String current = System.getProperty("user.dir");

        System.out.println(String.format("current=%s", current));

        // html 文件路径
        File index = Paths.get(current, "..", "index.html").toFile();
        if (!index.exists()) {
            System.out.println(String.format("file not exist,file=%s", index.getAbsolutePath()));
            return;
        }

        try {
            Document doc = Jsoup.parse(index, "UTF-8");
            // 补全标记
            doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml);

            File file = Paths.get(current, String.format("java%s_%s.pdf", version, platform)).toFile();
            FileOutputStream stream = new FileOutputStream(file);

            PdfRendererBuilder builder = new PdfRendererBuilder();

            // NOTE 字体问题,文档中出现过的字段,需要手动加载字体
            builder.useFont(Paths.get(current, "..", "fonts", "simsun.ttc").toFile(), "SimSun");
            builder.useFont(Paths.get(current, "..", "fonts", "msyh.ttc").toFile(), "font-test");
            builder.useFont(Paths.get(current, "..", "fonts", "msyh.ttc").toFile(), "Microsoft YaHei UI");

            // NOTE 设置根目录
            String baseUrl = Paths.get(current, "..").toUri().toString();
            builder.withHtmlContent(doc.html(), baseUrl);

            builder.toStream(stream);
            builder.run();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}